# *_*coding:utf-8 *_*
import time
# 获取一个可编历对象，使用它可以逐个获取匹配的文件路径名
from urllib.parse import urljoin, urlparse
from xmlrpc.client import ServerProxy

# 适用于存储数据对象
from dataclasses import dataclass

from py3utils.common_util import humanReadSecond
from base_m3u8 import DownLoad_M3U8, enough_free_space
from logger import logger



@dataclass
class TapToDualM3u8(DownLoad_M3U8):
    @staticmethod
    def get_natsorted_ts(ts_path):
        # 0.ts 1.ts 2.ts 3.ts 为开头广告
        # return DownLoad_M3U8.get_natsorted_ts(ts_path)[4:]
        return DownLoad_M3U8.get_natsorted_ts(ts_path)


class TapToDualDl(object):
    def __init__(self, host="127.0.0.1", port=8888):
        self.server = ServerProxy(f"http://{host}:{port}")
        self.ts_path = "../tmp"
        self.out_path = r"C:\download\TapToDual"

    def get_info(self):
        return self.server.get_info()

    def set_is_download(self, vodid):
        return self.server.set_is_download(vodid)

    def single_download(self):
        start = time.time()
        # proxies = {'sock5': '127.0.0.1:10808', 'http': '127.0.0.1:10809', 'https': '127.0.0.1:10809'}
        proxies = {}
        info = self.get_info()
        if not info:
            return False
        raw_content = info.get("m3u8_info")
        file_name = info.get("title")
        vodid = info.get("vodid")
        for k, v in info.items():
            if k in ["m3u8_info"]:
                continue
            logger.info(f"{k}:{v}")

        baseuri = info.get("baseuri")
        logger.info(f"baseuri:{baseuri}")
        if not baseuri:
            return False

        check_exist = info.get("check_exist") or False

        M3U8 = TapToDualM3u8(
            file_name=file_name,
            content=raw_content,
            out_path=self.out_path,
            base_uri=baseuri,
            ts_path=self.ts_path,
            proxies=proxies,
            max_workers=5,
            check_all_ts=False,
            check_exist=check_exist,
            auto_select_playlist=True,
        )
        # M3U8.download_all_ts = M3U8.download_all_ts2
        M3U8.download_all_ts = M3U8.download_all_ts3
        M3U8.run()
        self.set_is_download(vodid)
        logger.info('耗时:{}'.format(humanReadSecond(time.time() - start)))
        return True

    def all_download(self):
        while True:
            if not enough_free_space(self.ts_path) or not enough_free_space(self.out_path):
                break
            o = self.single_download()
            if o is False:
                break


if __name__ == '__main__':
    taptodualdl = TapToDualDl()
    # logger.info(taptodualdl.get_info())  # 调用函数1并传参
    # taptodualdl.single_download()
    # taptodualdl.set_is_download(4599)
    # taptodualdl.set_is_download(42043)
    taptodualdl.all_download()
    # merge_all_ts(r"D:\WorkSpace_PC\tmp")
